//回调
let id = location.search.substring('4')
// console.log(id)
$.ajax({
    url: '/my/category/list',
    success: function (res) {
        if (res.status === 0) {
            let str = ''
            res.data.forEach(item => {
                str += `<option value="${item.id}">${item.name}</option>`
            })
            $('select').html(str)
            let form = layui.form
            form.render()
            //因为ajax异步的原因,会导致加载事件先后顺序不一致
            $.ajax({
                url: '/my/article/' + id,
                success: function (res) {
                    if (res.status === 0) {
                        console.log('----------')
                        console.log(res.data)
                        let form = layui.form
                        form.val('edit', res.data)
                        let url = baseURL + '/' + res.data.cover_img
                        image.cropper('replace',url)
                    }
                }
            })
        }
    }
})
// $('form').on('submit', function (e) {
//     e.preventDefault()
//     $.ajax({
//         type: 'type',
//         url: '/my/article/update',
//         success: function (res) {
//             console.log(res)
//         }
//     })
// })
initEditor()
let image = $('#image')
let option = {
    aspectRatio: 400 / 280,
    autoCropArea: 1,
    preview: '.img-preview' // 指定预览区的类名（选择器）
}
image.cropper(option)

$('button:contains("选择封面")').on('click', function () {
//    alert(123)
    $('#file').trigger('click')
})
$('#file').on('change', function () {
    if (this.files.length > 0) {
        let objFile = this.files[0]
        let url = URL.createObjectURL(objFile)
        image.cropper('replace',url)
    }
})

$('form').on('submit', function (e) {
    e.preventDefault()
    // console.log(objFile)
    let fd = new FormData(this)
    fd.append('id', id)
    fd.set('content', tinyMCE.activeEditor.getContent())
    let canvas = image.cropper('getCroppedCanvas', { width: 400, height: 280 })
    // fd.append('cover_img', objFile)
    
    canvas.toBlob(function (blob) {
        fd.append('cover_img', blob)
        $.ajax({
            type: 'POST',
            url: '/my/article/update',
            data: fd,
            processData: false,
            contentType: false,
            success: function (res) {
                if (res.status === 0) {
                    // layer.msg(res.message)
                    layer.msg(res.message, { time: 3000 }, function () {
                        location.href = './list.html'
                    })
                    // location.href = './list.html'
                }
             console.log(res)
            }
        })
    })
})


